<template>
  <Dialog ref="dialog" title="志愿表" :isSendBus="true" custom-class="styleCss">
    <el-tabs
      v-model="activeName"
      class="demo-tabs"
      @tab-click="handleClick"
      v-loading="isRequest"
    >
      <el-tab-pane label="专家" name="first">
        <expertList
          :volunteerList="volunteerList"
          @onClickOptionItem="onClickOptionItem"
        ></expertList>
      </el-tab-pane>
      <el-tab-pane label="学生" name="second">
        <studentList
          :volunteerList="volunteerList"
          @onClickOptionItem="onClickOptionItem"
        ></studentList>
      </el-tab-pane>
      <!-- <div class="right" style="margin-top: 20px">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="pageData.page"
            v-model:page-size="pageData.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total"
            @size-change="getzybList"
            @current-change="getzybList"
          />
        </el-config-provider>
      </div> -->
    </el-tabs>
    <template #footer>
      <div class="right" style="margin-top: 20px; float: right">
        <el-config-provider :locale="zhCn">
          <el-pagination
            v-model:current-page="pageData.page"
            v-model:page-size="pageData.pageSize"
            :page-sizes="[10, 20, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total"
            @size-change="getzybList"
            @current-change="getzybList"
          />
        </el-config-provider>
      </div>
    </template>
  </Dialog>

  <el-dialog
    v-model="centerDialogVisible"
    title="最终方案"
    width="500"
    align-center
    class="lastProgramme"
  >
    <span v-if="groupId !=0 && row.is_subscriber==0 && finalSchemeStatus ==0 " style="display: inline-block; margin: 20px 0">
      是否确认将此方案设置为最终方案？但要收取{{cost}}元费用确定最终方案
    </span>
    <!-- <span v-else-if="finalSchemeStatus == 0 && row.is_subscriber!=0"  -->
    <span v-else-if="finalSchemeStatus == 0" 
      style="display: inline-block; margin: 20px 0"  >
      是否确认将此方案设置为最终方案？
    </span>
    <span v-else style="display: inline-block; margin: 20px 0"
      >是否取消将此方案设置为最终方案？
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="setFinalPlan">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <volundeerDetails ref="volundeerDetailsRef"></volundeerDetails>
</template>

<script setup>
import volundeerDetails from '../../volunteer/module/volunteerDetails.vue';
import Dialog from '@/components/Dialog/Dialog.vue';
import studentList from './studentList.vue';
import expertList from './expertList.vue';
import { ref, watch } from 'vue';
import { zyList } from '@/api/leader/Filling.js';
import { useRouter } from 'vue-router';
import { zySave, finalPlan,expenditure } from '@/api/appv2/appv2.js'; //unsubmit
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import { ElMessage } from 'element-plus';

const router = useRouter();
// const indexPosition = ref()
const dialog = ref(null);
const activeName = ref('first');
const volunteerList = ref([]);
const cost = ref() // 费用
const isRequest = ref(false);
const volundeerDetailsRef = ref(null);
const centerDialogVisible = ref(false);
const finalSchemeStatus = ref() // 判断是否是确定最终方案
const { id: teacherId, groupId } = JSON.parse(
  localStorage.getItem('userDateInfo')
);
// console.log(groupId,"kjsdjkasdh");
const isLoading = ref(false);
const row = ref()
// 设置最终方案点击的index
const setFinalPlanIndex = ref(0);
// const page = ref(1)

const pageData = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
});
// 父级传递的学生数据
const studentData = ref({});
// 学生信息
const studentInfo = ref({});
const props = defineProps({
  row:{
    type:Number,
    default: {}
  },
});
watch(
  ()=>props.row,
  (newVal)=>{
    row.value = newVal
    localStorage.setItem('is_subscriber',props.row.is_subscriber)
    // const is_subscriberId = JSON.parse(localStorage.getItem('is_subscriberId'))?? 0;
    // if()
    // localStorage.setItem('is_subscriberId',props.row.id)
  }
);
const expenditureFun = () => {
  expenditure().then((res)=>{
    cost.value = res.data.price
  })
}
expenditureFun()
function openChange(val) {
  console.log(val.student.section, 'val');

  // 打开组件弹窗
  studentData.value = val;
  studentInfo.value = val.student;

  dialog.value.openChange();
  activeName.value = 'first';
  localStorage.setItem('section', val.student.section);
  getzybList();
}
// const Cancelfinalplan = (index) => {
//   indexPosition.value = index
//   centerDialogVisible.value = true
//   // unsubmit(index).then((res)=>{
//   //   console.log(res);
//   // })
// }
// 获取志愿表列表
function getzybList() {
  let section = localStorage.getItem('section');
  if (isRequest.value) return;
  isRequest.value = true;

  let data = {
    fronttype: 3,
    page: pageData.page,
    pageSize: pageData.pageSize,
    studentId: studentData.value.studentId,
    mod: 1,
  };

  if (activeName.value == 'first') {
    data['createFrom'] = '1,2';
  } else {
    data['createFrom'] = '0';
    data['isTeacherSee'] = 1;
  }

  zyList(data)
    .then((res) => {
      isRequest.value = false;
      let data = JSON.parse(JSON.stringify(res.data));
      pageData.total = data.total;
      if (pageData.page == 1) {
        volunteerList.value = data.data;
      } else {
        volunteerList.value = [...volunteerList.value, ...data.data];
      }
      volunteerList.forEach((item) => {
        $set(item, 'section', section);
      });
    })
    .catch(() => {
      isRequest.value = false;
    });
}

function handleClick(val) {
  // 切换组件信息
  if (activeName.value != val.paneName) {
    volunteerList.value = [];
    activeName.value = val.paneName;
    getzybList();
  }
}

/**
 * 点击志愿表操作选项
 * @param {Number} index 下标
 * @param {Number} type 操作类型 0-查看 1-最终方案 2-同步至学生 3-删除 4-复制到专家
 */
function onClickOptionItem(index, type, row) {
  finalSchemeStatus.value = row.finalSchemeStatus
  console.log('finalSchemeStatus.value', finalSchemeStatus.value);
  switch (type) {
    case 0: // 查看志愿表
      if (activeName.value == 'first') {
        seeVolunteer(index);
      } else {
        let volunteer = volunteerList.value[index];
        let body = {
          index: volunteer.index,
          zy_type: volunteer.zy_type,
          studentData: studentData.value,
        };

        volundeerDetailsRef.value.openChange(body);
      }
      break;
    case 1: // 最终方案
      finalScheme(index);
      break;
    case 2: // 同步至学生
      syncVolunteerToStudent(index, row);
      break;
    case 3: // 删除
      deleteVolunteer(index);
      break;
    case 4: // 复制到专家
      copyVolunteerToExpert(index);
      break;
    case 6: // 取消最终审核
      // Cancelfinalplan(index)
      finalScheme(index);
      break;
    default:
      break;
  }
}

/**
 * 查看志愿表
 * @param {Number} index 志愿表下标
 */
function seeVolunteer(index) {
  let volunteer = volunteerList.value[index];
  let body = JSON.stringify({
    index: volunteer.index,
    zy_type: volunteer.zy_type || volunteer.zyType,
    status: volunteer.status,
    studentData: studentData.value,
  });
  body = btoa(encodeURIComponent(body));
  if (volunteer.is_danzhao == 1 || volunteer.is_danzhao == 2) {
    router.push({
      path: '/leader/savevolunteerd',
      query: {
        data: body,
      },
    });
  } else {
    router.push({
      path: '/leader/savevolunteer',
      query: {
        data: body,
      },
    });
  }
}

/**
 * 最终方案
 * @param {Number} index 志愿表下标
 */
function finalScheme(index) {
  setFinalPlanIndex.value = index;
  centerDialogVisible.value = true;  
}
// 做一个节流函数
const throttle = (fn, delay) => {
      let lastTime = 0;
      return function(...args) {
        const now = new Date().getTime();
        if (now - lastTime >= delay) {
          lastTime = now;
          fn(...args);
        }
      };
    };
// 设置最终方案
const setFinalPlan = throttle(setFinalPlan1, 2000);
function setFinalPlan1() {
  const { phone, index } = volunteerList.value[setFinalPlanIndex.value]; 
  if (isLoading.value) return; // 防止重复请求
  isLoading.value = true;
  setTimeout(() => {
    finalPlan({
      phone,
      index,
    })
    .then((res) => {
      ElMessage({
        type: 'success',
        message: res.msg,
      });
      centerDialogVisible.value = false;     
      getzybList();
      localStorage.setItem('is_subscriber',1)
      row.value.is_subscriber = JSON.parse(localStorage.getItem('is_subscriber'));
      console.log(row.value,"row.value");
    })
    .catch((err) => {
      console.log('err:', err);
    });
    isLoading.value = false;
  }, 2000); // 模拟延迟
   
    //   phone,
    //   index,
    // })
    // .then((res) => {
    //   ElMessage({
    //     type: 'success',
    //     message: res.msg,
    //   });
    //   centerDialogVisible.value = false;     
    //   getzybList();
    //   localStorage.setItem('is_subscriber',1)
    //   row.value.is_subscriber = JSON.parse(localStorage.getItem('is_subscriber'));
    //   console.log(row.value,"row.value");
    // })
    // .catch((err) => {
    //   console.log('err:', err);
    // });
}

/**
 * 同步志愿表到学生
 * @param {Number} index 志愿表下标
 */
function syncVolunteerToStudent(index, row) {
  console.log(row, 'roww');

  if (row.is_danzhao == 1 || row.is_danzhao == 2) {
    ElMessage({
      type: 'error',
      message: '单招志愿表不能同步至学生',
    });
    return;
  }
  let volunteer = volunteerList.value[index];
  volunteer.isStudentSee = volunteer.isStudentSee == 1 ? 0 : 1;

  let data = {};
  (data['index'] = volunteer.index),
    (data['studentId'] = studentData.value.studentId);
  data['isStudentSee'] = volunteer.isStudentSee;
  data['teacherId'] = teacherId;
  data['groupId'] = groupId;
  zySave(data).then(() => {
    // 修改成功
  });
}

/**
 * 删除志愿表
 * @param {Number} index 志愿表下标
 */
function deleteVolunteer(index) {
  let volunteer = volunteerList.value[index];
  let data = {};
  (data['index'] = volunteer.index),
    (data['studentId'] = studentData.value.studentId);
  data['operate'] = 'del';
  data['teacherId'] = teacherId;
  data['groupId'] = groupId;
  zySave(data).then(() => {
    // 删除成功
    volunteerList.value.splice(index, 1);
  });
}

/**
 * 复制志愿表到专家
 * @param {Number} index 志愿表下标
 */
function copyVolunteerToExpert(index) {
  let volunteer = volunteerList.value[index];
  zySave({
    index: volunteer.index,
    operate: 'copy',
    studentId: studentData.value.studentId,
    teacherId: teacherId,
    groupId: groupId,
  }).then(() => {
    ElMessage({
      type: 'success',
      message: '复制成功',
    });
  });
}

defineExpose({
  openChange,
});
</script>
<style lang="scss" scoped>
:deep(.el-tabs__item.is-active) {
  color: #1d2129;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  height: 3px;
  background-color: #1d2129;
}

:deep(.el-tabs__item) {
  height: 52px;
  line-height: 52px;
  color: #4e5969;
  font-size: 20px;
}
:deep(.el-dialog__footer) {
  display: unset !important;
}
:deep(.el-dialog__body) {
  overflow-y: hidden;
}
</style>
